/**
 * _oo0oo_
 * o8888888o
 * 88" . "88
 * (| - - |)
 * 0\ 3 /0
 * ___/`---'\___
 * .' \\| |// '.
 * / \\||| : |||// \
 * / -||||| -:- |||||- \
 * | | \\\ - /// | |
 * | \_| ''\---/'' | _/|
 * \ .-\__ '_' __/ -. /
 * ____'. .' /--.--\ . .'___
 * ."" '< `.____\_<|>_/____.' >' "".
 * | | : `- \`.;`\ _ /`;.`/ - ` : | |
 * \ \ `-. \_ __\ /__ _/ .-` / /
 * =====`-.____`-.___ \____—____/ ___.-`____.-`=====
 * <p>
 * <p>
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * 佛祖保佑 永无bug
 * <p>
 * 声明：以上图像从JFinal群中抄的
 * <p>
 * Copyright (c) 2014-2015, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.config;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.aop.AopManager;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.Const;
import com.jfinal.core.JFinal;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.json.FastJsonFactory;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.sql.ParaDefDirective;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.render.ViewType;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;

import cn.hg.base.jfinal.directive.AutoDirectiveEngine;
import cn.hg.jfsa.common.JfsaConstants;
import cn.hg.jfsa.common.JfsaLogManager;
import cn.hg.jfsa.common.OptionInitializer;
import cn.hg.jfsa.common.controller.CaptchaController;
import cn.hg.jfsa.core.handler.JfsaFakeStaticHandler;
import cn.hg.jfsa.core.handler.JfsaSessionHandler;
import cn.hg.jfsa.core.interceptor.JfsaControllerInterceptor;
import cn.hg.jfsa.core.service.OptionServiceApi;
import cn.hg.jfsa.manage.controller.login.ManageLoginController;
import cn.hg.jfsa.manage.interceptor.HttpInterceptor;
import cn.hg.jfsa.manage.interceptor.JfsaManageInterceptor;
import cn.hg.jfsa.manage.route.ManageRoutes;
import cn.hg.jfsa.manage.service.JfsaOptionService;
import cn.hg.jfsa.model._MappingKit;
import cn.hg.jfsa.web.route.WebAppRoutes;
import cn.hg.jfsa.web.theme.ThemeRenderFactory;

/**
 * @author golly
 */
public class JFSimpleAdminConfig extends JFinalConfig {

	private static Prop p = PropKit.use("simple_admin_config.txt");

	public static DruidPlugin createDruidPlugin () {
		return new DruidPlugin(JFSimpleAdminConfig.p.get("jdbcUrl"), JFSimpleAdminConfig.p.get("user"),
			JFSimpleAdminConfig.p.get("password").trim());
	}

	public static void main (String[] args) {
		UndertowServer.start(JFSimpleAdminConfig.class);
	}

	private Log log = Log.getLog(this.getClass());
	private WallFilter wall;

	/*
	 * (non-Javadoc)
	 * @see
	 * com.jfinal.config.JFinalConfig#configConstant(com.jfinal.config.Constants)
	 */
	@Override
	public void configConstant (Constants me) {
		me.setDevMode(JFSimpleAdminConfig.p.getBoolean("devMode", false));
		me.setEncoding("UTF-8");
		me.setError401View("/manage/_error/401.html");
		me.setError403View("/manage/_error/403.html");
		me.setError404View("/manage/_error/404.html");
		me.setError500View("/manage/_error/500.html");
		me.setBaseUploadPath(JFSimpleAdminConfig.p.get("baseUploadPath", JfsaConstants.JFSA_UPLOAD_PATH));
		me.setViewType(ViewType.JFINAL_TEMPLATE);
		me.setJsonFactory(new FastJsonFactory());
		// 用主题渲染工厂替换原工厂
		me.setRenderFactory(new ThemeRenderFactory("/manage", "/captcha"));
		me.setInjectDependency(true);
		me.setMaxPostSize(100 * Const.DEFAULT_MAX_POST_SIZE);
		me.setReportAfterInvocation(true);
	}

	/*
	 * (non-Javadoc)
	 * @see com.jfinal.config.JFinalConfig#configEngine(com.jfinal.template.Engine)
	 */
	@Override
	public void configEngine (Engine me) {
		me.setDevMode(JFSimpleAdminConfig.p.getBoolean("engineDevMode", false));
		AutoDirectiveEngine.register(me, true, "cn.hg");
	}

	/*
	 * (non-Javadoc)
	 * @see com.jfinal.config.JFinalConfig#configHandler(com.jfinal.config.Handlers)
	 */
	@Override
	public void configHandler (Handlers me) {
		me.add(new ContextPathHandler("ctx"));
		me.add(new DruidStatViewHandler("/manage/druid", new JfsaDruidStatViewAuth("/manage/druid")));
		me.add(new JfsaSessionHandler());
		me.add(new JfsaFakeStaticHandler(".html", "/manage", "/captcha"));
	}

	/*
	 * (non-Javadoc)
	 * @see com.jfinal.config.JFinalConfig#configInterceptor(com.jfinal.config.
	 * Interceptors)
	 */
	@Override
	public void configInterceptor (Interceptors me) {
		// me.add(new TxByActionKeyRegex("save*|upd*|update*|del*|batch*"));
		me.add(new HttpInterceptor());
		me.add(new JfsaControllerInterceptor());
		me.add(new JfsaManageInterceptor());
	}

	/*
	 * (non-Javadoc)
	 * @see com.jfinal.config.JFinalConfig#configPlugin(com.jfinal.config.Plugins)
	 */
	@Override
	public void configPlugin (Plugins me) {
		// 缓存插件
		EhCachePlugin cp = new EhCachePlugin();
		// 数据库连接池插件
		this.wall = new WallFilter();
		this.wall.setDbType(JdbcConstants.MYSQL);
		DruidPlugin druidPlugin = JFSimpleAdminConfig.createDruidPlugin();
		druidPlugin.addFilter(this.wall);
		druidPlugin.addFilter(new StatFilter());
		// 数据操作插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
		arp.setShowSql(JFSimpleAdminConfig.p.getBoolean("devMode", false));
		arp.setDialect(new MysqlDialect()); // 设置SQL方言
		_MappingKit.mapping(arp); // 映射Model
		arp.addSqlTemplate("/sql/jfsa.manage.sql"); // 加载sql模板
		arp.addSqlTemplate("/sql/jfsa.web.sql");
		// 注册支持默认参数值的标签
		arp.getEngine().addDirective("paradef", ParaDefDirective.class);
		// 注册各个插件
		me.add(cp);
		me.add(druidPlugin);
		me.add(arp);
	}

	/*
	 * (non-Javadoc)
	 * @see com.jfinal.config.JFinalConfig#configRoute(com.jfinal.config.Routes)
	 */
	@Override
	public void configRoute (Routes me) {
		// 非业务控制器
		me.add("/manage/login", ManageLoginController.class);
		me.add("/captcha", CaptchaController.class);
		// 管理端Routes
		me.add(new ManageRoutes());
		// 业务端Routes
		me.add(new WebAppRoutes());
	}

	// 系统启动完成后回调
	@Override
	public void onStart () {
		// wall.getConfig().setSelectUnionCheck(false); // 解除union关键字检查
		// wall.getConfig().setMultiStatementAllow(true); // 允许多语句SQL
		// Option初始化前先将Service注册到拦截器中去
		AopManager.me().addMapping(OptionServiceApi.class, JfsaOptionService.class);
		// 初始化系统设置
		OptionInitializer.me().init();
		// **********************************************************************
		StringBuilder startStr = new StringBuilder("\r\n")
			.append("                       _oo0oo_ \r\n")
			.append("                      o8888888o \r\n")
			.append("                      88\" . \"88 \r\n")
			.append("                      (| - - |) \r\n")
			.append("                      0\\  3  /0 \r\n")
			.append("                    ___/`---'\\___ \r\n")
			.append("                  .' \\\\|     |// '. \r\n")
			.append("                 / \\\\|||  :  |||// \\ \r\n")
			.append("                / -||||| -:- |||||- \\ \r\n")
			.append("               |   | \\\\\\  -  /// |   | \r\n")
			.append("               | \\_|  ''\\---/''  | _/|  \r\n")
			.append("               \\  .-\\__  '_'  __/ -. / \r\n")
			.append("            ____'. .'  /--.--\\    . .' \r\n")
			.append("          .\"\" '< `.____\\_<|>_/____.' >' \"\". \r\n")
			.append("          | | : `- \\`.;`\\ _ /`;.`/ - ` : | | \r\n")
			.append("          \\ \\ `-.   \\_ __\\ /__ _/   .-`  / / \r\n")
			.append("  =====`-.____`-.___ \\____—____/ ___.-`____.-`===== \r\n")
			.append("\r\n")
			.append("后台服务启动成功，望佛祖保佑没有Bug！");
		this.log.info(startStr.toString());
		// 打印所有Action
		this.log.debug("所有Action：" + JFinal.me().getAllActionKeys().toString());
		// System.out.println("所有Action：" + JFinal.me().getAllActionKeys().toString());
	}

	// 系统关闭之前回调
	@Override
	public void onStop () {
		// 清空日志
		JfsaLogManager.me().flush();
		this.log.info("系统关闭！！！");
	}

}
